package service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;

import model.Encrypter;
import model.EncrypterDisposition;
import model.EncrypterTransformation;

public class EncService {

	private Encrypter enc;

	public EncService() {
//		enc = new EncrypterTransformation();
		enc = new EncrypterDisposition();
	}

	public String decode(File f) throws IOException {
		FileInputStream fis = new FileInputStream(f);
		String path = f.getAbsolutePath();
		String file = f.getName();
		int indexOf = path.indexOf(file);
		String path2 = path.substring(0, indexOf);
		String[] split2 = file.split("\\.");
		List<String> list = Arrays.asList(split2);
		String fileEnding = list.get(list.size() - 1);
		String beforeEnding = list.get(0);
		boolean firstEnc = true;
		for (int i = 1; i < list.size() - 1; i++) {
			if(list.get(i).equals("enc") && firstEnc ) {
				firstEnc = false;
			} else {
				beforeEnding += "." + list.get(i);
			}
		}
		File fileout = new File(path2 + beforeEnding + "." + fileEnding);
		FileOutputStream fos = new FileOutputStream(fileout);
		enc.decrypt(fis, fos);
		fis.close();
		fos.close();
		return fileout.getAbsolutePath();
	}

	public String encode(File f) throws IOException {
		FileInputStream fis = new FileInputStream(f);
		String path = f.getAbsolutePath();
		String file = f.getName();
		int indexOf = path.indexOf(file);
		String path2 = path.substring(0, indexOf);
		String[] split2 = file.split("\\.");
		List<String> list = Arrays.asList(split2);
		String fileEnding = list.get(list.size() - 1);
		String beforeEnding = list.get(0);
		for (int i = 1; i < list.size() - 1; i++)
			beforeEnding += "." + list.get(i);
		File fileout = new File(path2 + beforeEnding + ".enc." + fileEnding);
		FileOutputStream fos = new FileOutputStream(fileout);
		enc.encrypt(fis, fos);
		fis.close();
		fos.close();
		return fileout.getAbsolutePath();
	}

}
